package com.hmall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.hmall.common.client.ItemClient;
import com.hmall.common.dto.Item;
import com.hmall.common.dto.ItemDoc;
import com.hmall.common.dto.PageDTO;
import com.hmall.search.pojo.RequestParams;
import com.hmall.search.service.ISearchService;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service
public class ISearchServiceImpl implements ISearchService {
    @Autowired
    private ItemClient itemClient;
    @Autowired
    private RestHighLevelClient restHighLevelClient;
    @Override
    public Map<String, List<String>> getFilters(RequestParams params) {
        try {
            SearchRequest request = boolQueryBuilder(params);
            request.source().size(0);
            request.source().aggregation(
                    AggregationBuilders.terms("brandAgg").field("brand").size(20)
            );
            request.source().aggregation(
                    AggregationBuilders.terms("categoryAgg").field("category").size(20)
            );
            SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
            Map<String, List<String>> map = new HashMap<>(2);
            Aggregations aggregations = response.getAggregations();
            Terms brandAgg = aggregations.get("brandAgg");
            List<String> brandList = new ArrayList<>();
            for (Terms.Bucket bucket : brandAgg.getBuckets()) {
                String key = bucket.getKeyAsString();
                brandList.add(key);
            }
            map.put("brand", brandList);
            Terms categoryAgg = aggregations.get("categoryAgg");
            List<String> categoryList = new ArrayList<>();
            for (Terms.Bucket bucket : categoryAgg.getBuckets()) {
                String key = bucket.getKeyAsString();
                categoryList.add(key);
            }
            map.put("category", categoryList);
            return map;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public PageDTO<ItemDoc> search(RequestParams params) {
        try{
            SearchRequest request = boolQueryBuilder(params);
            String sortBy = params.getSortBy();
            if ("sold".equals(sortBy)) {
                request.source().sort(sortBy, SortOrder.DESC);
            } else if ("price".equals(sortBy)) {
                request.source().sort(sortBy, SortOrder.ASC);
            }
            SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
            PageDTO pageDTO = handleResponse(response);
            return pageDTO;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void deleteItemById(Long id) {
        try {
            // 1.准备Request
            DeleteRequest request = new DeleteRequest("item", id.toString());
            // 2.发请求
            restHighLevelClient.delete(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void saveItemById(Long id) {
        try {
            // 1.查询商品数据
            Item item = itemClient.getById(id);
            // 2.准备Request
            IndexRequest request = new IndexRequest("item").id(id.toString());
            // 3.准备DSL
            request.source(JSON.toJSONString(new ItemDoc(item)), XContentType.JSON);
            // 4.发送请求
            restHighLevelClient.index(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    private PageDTO handleResponse(SearchResponse response) {
        SearchHits searchHits = response.getHits();
        // 4.1.获取总条数
        long total = searchHits.getTotalHits().value;
        // 4.2.文档数组
        SearchHit[] hits = searchHits.getHits();
        // 4.3.遍历
        List<ItemDoc> list=new ArrayList<>();
        for (SearchHit hit : hits) {
            // 获取文档source
            String json = hit.getSourceAsString();
            // 反序列化
            ItemDoc itemDoc = JSON.parseObject(json, ItemDoc.class);
            list.add(itemDoc);
        }
        return new PageDTO<ItemDoc>(total,list);
    }
    private SearchRequest boolQueryBuilder(RequestParams params){
        SearchRequest request = new SearchRequest("item");
        BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
        if (StringUtils.isEmpty(params.getKey()) || params.getKey() == "") {
            queryBuilder.must(QueryBuilders.matchAllQuery());
        } else {
            queryBuilder.must(QueryBuilders.matchQuery("all", params.getKey()));
        }
        if (!StringUtils.isEmpty(params.getCategory()) && params.getCategory() != "") {
            queryBuilder.filter(QueryBuilders.termQuery("category", params.getCategory()));
        }
        if (!StringUtils.isEmpty(params.getBrand()) && params.getBrand() != "") {
            queryBuilder.filter(QueryBuilders.termQuery("brand", params.getBrand()));
        }
        if (params.getMinPrice() != null && params.getMaxPrice() != null) {
            queryBuilder.filter(QueryBuilders.rangeQuery("price").gte(params.getMinPrice() * 100).lte(params.getMaxPrice() * 100));
        }
        request.source().query(queryBuilder);
        int page = params.getPage();
        int size = params.getSize();
        request.source().from((page - 1) * size).size(size);
        return request;
    }
}
